<?php
namespace app\applet\controller;

use think\facade\View;
use think\facade\Session;
use think\captcha\facade\Captcha;
use app\applet\model\Applet as AppletModel;
use app\applet\model\Setting as SettingModel;
use think\facade\Config;


/**
 * 登录小程序管理中心
 */
class Passport extends Controller
{
    /**
     * 生成验证码
     **/
    public function captcha()
    {
        return Captcha::create();
    }

    /**
     * 用户登录
     */
    public function login()
    {
        if (!$this->request->isAjax()) {
            if(!empty($this->user) AND (int)$this->user['is_login'] == 1 AND isset($this->user['applet']) AND !empty($this->user['applet'])){
                return redirect(url('index/index'));  
            }
            View::layout(false);
            View::assign([
                'web' => SettingModel::getItem('web',0),    //站点设置
                'version' => Config::get('app.hemaphp.version'),
            ]);
            return View::fetch();
        }
        $model = new AppletModel;
        if ($model->login($this->postData('data'))) {
            return $this->renderSuccess('登录成功', url('index/index'));
        }
        $error = $model->getError() ?: '登录失败';
        return $this->renderError($error);
    }
    
    /**
     * 退出登录
     */
    public function logout()
    {
        Session::delete('hema_applet');// 清空登录状态
        return redirect(url('passport/login'));
    }

}